﻿using BLL;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using webui.Models;
using Tools;
using webui.ViewModel;
using SqlSugar;

namespace webui.Areas.Admin.Controllers
{
    public class SysController : Controller
    {
        public PermissionBLL ipemissBLL = new PermissionBLL();

        #region 1.0 权限列表 视图 +Permission()
        [HttpGet]
        /// <summary>
        /// 权限列表 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Permission()
        {
            return View();
        }
        #endregion
         
        [HttpPost]
        /// <summary>
        /// 权限列表 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPermData()
        {
            //获取页容量
            int pageSize = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int pageIndex = int.Parse(Request.Form["page"]);

     
            // 查询分页数据

            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = 0
            };
            var list = ipemissBLL.GetPageList(p => p.pParent == 2 && p.pIsDel == false, page, p => p.Id, OrderByType.Desc);

            //2 生成规定格式的 json字符串发回 给 异步对象
            DataGridModel dgModel = new DataGridModel()
            {
                total = page.PageCount,
                rows = list,
                footer = null
            };
            return Json(dgModel);
        } 
       
        [HttpGet]
        /// <summary>
        /// 子权限列表 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult PermissionSon()
        {
            //获取父权限id
            ViewBag.pid = int.Parse(Request.QueryString["id"]);
            return View();
        } 


         
        [HttpPost]
        /// <summary>
        /// 查询子权限列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult PermissionSon(FormCollection form)
        {
            //获取页容量
            int pageSize = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int pageIndex = int.Parse(Request.Form["page"]);
            //获取父权限id
            int parentMenuId = int.Parse(Request.QueryString["id"]);
            // 查询分页数据

            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = 0
            };
            var list = ipemissBLL.GetPageList(p => p.pParent == parentMenuId && p.pIsDel == false, page, p => p.Id, OrderByType.Desc);

            //2 生成规定格式的 json字符串发回 给 异步对象
             DataGridModel dgModel = new DataGridModel()
            {
                total = page.PageCount,
                rows = list,
                footer = null
            };
            return Json(dgModel);
        } 

        #region 0.1 生成 父菜单 下拉框 html字符串 -string GetParentMenuDrowDownListHtml(int pId)
        /// <summary>
        /// 生成 父菜单 下拉框 html字符串
        /// </summary>
        /// <returns></returns>
        string GetParentMenuDrowDownListHtml(int pId)
        {
            //1.查询所有的父菜单 

            var list = ipemissBLL.GetList(p => p.pParent == 2);
             

            System.Text.StringBuilder sb = new StringBuilder("<select name='pParent'><option value=2>父菜单</option>", 1000);
            list.ForEach(p =>
            {
                if (pId == p.Id)
                    sb.AppendLine("<option selected value='" + p.Id + "'>" + p.pName + "</option>");
                else
                    sb.AppendLine("<option value='" + p.Id + "'>" + p.pName + "</option>");
            });
            sb.AppendLine("</select>");

            return sb.ToString();
        }
        #endregion

        #region 0.2 设置新增和修改通用的下拉框数据 -void SetDropDonwList()
        /// <summary>
        /// 设置新增和修改通用的下拉框数据
        /// </summary>
        void SetDropDonwList()
        {
            //准备请求方式下拉框数据
            ViewBag.httpMethodList = new List<SelectListItem>() {
             new SelectListItem(){ Text="Get",Value="1"},
             new SelectListItem(){ Text="Post",Value="2"},
             new SelectListItem(){ Text="Both",Value="3"}
            };

            /*
             0-无操作 1-easyui连接 2-打开新窗体
             */
            // ViewBag.operationList = new List<SelectListItem>() { 
            // new SelectListItem(){ Text="无操作",Value="0"},
            // new SelectListItem(){ Text="easyui连接",Value="1"},
            // new SelectListItem(){ Text="打开新窗体",Value="2"}
            //};
        }
        #endregion

        #region 1.2 加载 权限修改 窗体html +EditPermission()
        [HttpGet, AjaxRequest]
        /// <summary>
        /// 1.2 加载 权限修改 窗体html
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPermission(int id)
        {
            //根据id查询要修改的权限
            var model = ipemissBLL.GetList(p => p.Id == id).FirstOrDefault();
            SetDropDonwList();

            //将 权限对象 传给 视图 的 Model属性
            V_Permission vModel =model.MapTo<V_Permission, Permission>();
            return PartialView(vModel);
        }
        #endregion



        #region 1.2 权限修改 +EditPermission(MODEL.ViewModel.Permission model)
        [HttpPost, AjaxRequest]
        /// <summary>
        /// 1.2 权限修改
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPermission(Permission model)
        {

            //model.pRemark = viewmodel.pRemark; 

           bool res= ipemissBLL.Update(u => new Permission { pName = model.pName, pAreaName = model.pAreaName,
                pControlName = model.pControlName,
                pActionName = model.pActionName,
                pFormMethod = model.pFormMethod,
                pOrder = model.pOrder,
                pIsShow = model.pIsShow,
                pRemark = model.pRemark,
            }, u => u.Id == model.Id);
           
            if (res  )//return Redirect("/admin/sys/Permission?ok");
            {
                if (model.pParent > 1)
                {
                    return Redirect("/admin/sys/PermissionSon?id=" + model.pParent);
                }
                else//如果新增的是 父权限，则跳到父权限列表
                    return Redirect("/admin/sys/Permission");
            }
            else
                return Redirect("/admin/sys/Permission?err");
        }
        #endregion


        #region 1.3 显示 新增权限 表单代码 +AddPermission()
        [HttpGet]
        [AjaxRequest]
        /// <summary>
        /// 显示 新增权限 表单代码
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPermission()
        {
            int id = -1;
            if (Request["id"] != null)
            {
                int.TryParse(Request["id"].ToString(), out id);
            }


            SetDropDonwList();
            ViewBag.ParentMenuHtml = GetParentMenuDrowDownListHtml(id);
            return PartialView("EditPermission");
        }
        #endregion

        #region 1.3 新增权限 +AddPermission()
        [HttpPost]
        /// <summary>
        /// 新增权限
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPermission(Permission model)
        {
            model.pIsDel = false;
            model.pAddtime = DateTime.Now;
            model.pOperationType = 0;
            bool res = ipemissBLL.Insert(model);
            if (res )
            {
                //如果新增的是子权限，则调回 子权限列表，同时 把父权限id作为参数加入
                if (model.pParent > 2)
                {
                    return Redirect("/admin/sys/PermissionSon?id=" + model.pParent);
                }
                else//如果新增的是 父权限，则跳到父权限列表
                    return Redirect("/admin/sys/Permission");
            }
            else
                return Redirect("/admin/sys/Permission?err");
        }
        #endregion


        #region 1.4 删除权限 +DelPemission()
        /// <summary>
        /// 1.4 删除权限
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxRequest]
        public ActionResult DelPemission()
        {
            try
            {
                int id = int.Parse(Request.Form["id"]);
                ipemissBLL.DeleteById(id);
                return OperateContext.Current.RedirectAjax("ok", "删除成功~~~", null, "");
            }
            catch
            {
                return OperateContext.Current.RedirectAjax("err", "您现在删除的权限正在被角色使用，请先取消角色中的这个权限！", null, "");
            }

        }
        #endregion


    }
}